package com.hean.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class NetUtil {
	/**
	 * 获取url路径指定的网页代码
	 * @param urlPath
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String getTextContent(String urlPath,String encoding) throws Exception{
		URL url=new URL(urlPath);
		HttpURLConnection con=(HttpURLConnection) url.openConnection();
		con.setRequestMethod("GET");
		con.setConnectTimeout(6*1000);
		if(con.getResponseCode()==200){
			InputStream inputStream=con.getInputStream();
			byte[] data=readStream(inputStream);
			return new String(data,encoding);
		}
		return null;
		
	}

	private static byte[] readStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		byte[] buffer =new byte[1024];
		int len=-1;
		while((len=inputStream.read(buffer))!=-1){
			byteArrayOutputStream.write(buffer, 0, len);
		}
		return byteArrayOutputStream.toByteArray();
	}
	public static byte[] getImage(String urlpath) throws Exception{
		URL url=new URL(urlpath);
		HttpURLConnection con=(HttpURLConnection) url.openConnection();
		con.setRequestMethod("GET");
		con.setConnectTimeout(6*1000);
		if(con.getResponseCode()==200){
			InputStream inputStream=con.getInputStream();
			return readStream(inputStream);
		}
		return null;
	}
	/**
	 * 
	 * @param urlpath
	 * @param params
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static InputStream sendPostRequest(String urlpath,Map<String, String>params,String encoding) throws Exception{
		StringBuilder sb=new StringBuilder();
		for(Map.Entry<String, String> entry:params.entrySet()){
			sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encoding));
			sb.append('&');
		}
		sb.deleteCharAt(sb.length()-1);
		//String param="method=save&&id=67&name="+URLEncoder.encode("老张", "UTF-8");//发送过去的数据
		byte[] data=sb.toString().getBytes();
		URL url=new URL(urlpath);
		HttpURLConnection con=(HttpURLConnection) url.openConnection();
		con.setConnectTimeout(6*1000);
		con.setDoOutput(true);//发送post请求必须设置允许输出
		con.setUseCaches(false);//不使用cache
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Length", String.valueOf(data.length));
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		DataOutputStream dataOutputStream=new DataOutputStream(con.getOutputStream());
		dataOutputStream.write(data);
		dataOutputStream.flush();
		dataOutputStream.close();
		if(con.getResponseCode()==200){
			return con.getInputStream();
		}
		return null;
		
	}
	
	public void PostParamHttpClient() throws Exception{
		HttpPost httpPost=new HttpPost("url");
		List<NameValuePair> pairs=new ArrayList<NameValuePair>();//参数
		pairs.add(new BasicNameValuePair("id", "55"));
		pairs.add(new BasicNameValuePair("name", "老毕"));
		pairs.add(new BasicNameValuePair("method", "save"));
		httpPost.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8));
		DefaultHttpClient client=new DefaultHttpClient();//浏览器客户端
		HttpResponse response=client.execute(httpPost);
		InputStream stream=response.getEntity().getContent();
		
		
		byte[] data=readStream(stream);
		System.out.println(new String(data,"UTF-8"));
	}
}
